package cn.dxs.adt.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

import cn.dxs.adt.R;
import cn.dxs.adt.http.news.NewsEntry;
import cn.dxs.adt.utils.ClipboardUtil;
import cn.dxs.adt.utils.Util;

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {

    private List<NewsEntry> mList_news;

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView id;
        TextView newsContent;
        TextView createTime;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            this.id = itemView.findViewById(R.id.tv_id);
            this.newsContent = itemView.findViewById(R.id.tv_newsContent);
            this.createTime = itemView.findViewById(R.id.tv_createTime);
        }
    }

    public NewsAdapter(List<NewsEntry> newsEntries) {
        mList_news = newsEntries;
    }

    @NonNull
    @Override
    public NewsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_news, parent,false);
        ViewHolder holder = new ViewHolder(view);
        holder.newsContent.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                int position = holder.getLayoutPosition();
                NewsEntry newsEntry = mList_news.get(position);
                ClipboardUtil.copyContentToClipboard(newsEntry.newsContent);
                Toast.makeText(parent.getContext(), newsEntry.newsContent, Toast.LENGTH_SHORT).show();
                return false;
            }
        });
        return holder;
    }

    @Override
    public void onBindViewHolder(@NonNull NewsAdapter.ViewHolder holder, int position) {
        NewsEntry newsEntry = mList_news.get(position);
        holder.id.setText(String.valueOf(newsEntry.id));
        holder.createTime.setText(Util.getCreateTime(newsEntry.createTime));
        holder.newsContent.setText(newsEntry.newsContent);
    }

    @Override
    public int getItemCount() {
        return mList_news.size();
    }

    public void notifyDataSetChanged(List<NewsEntry> newsEntries) {
        mList_news.clear();
        mList_news = newsEntries;
        notifyDataSetChanged();
    }
}
